<script setup lang="ts">
import { ref, computed, reactive, watch } from 'vue'
import type { FormInst, FormItemRule, FormRules } from 'naive-ui'

const { add, update } = useUser()

defineOptions({ name: 'Modal' })

interface Props {
  /** 弹窗可见性 */
  visible: boolean
  /**
   * 弹窗类型
   * add: 新增
   * edit: 编辑
   */
  type?: 'add' | 'edit'
  /** 编辑的表格行数据 */
  model?: UserModel | null
  /** 重新加载表格数据 */
  load: Function
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'load'): void
}

const formRef = ref<HTMLElement & FormInst>()
const emit = defineEmits<Emits>()
const props = withDefaults(defineProps<Props>(), {
  type: 'add',
})

watch(
  () => props.visible,
  (newValue) => {
    if (newValue) {
      if (props.type == 'add') {
        Object.assign(formModel, defaultModel())
      } else if (props.type == 'edit' && props.model) {
        Object.assign(formModel, props.model)
      }
    }
  },
)
//是否显示弹窗
const modalVisible = computed({
  get() {
    return props.visible
  },
  set(visible) {
    emit('update:visible', visible)
  },
})

const title = computed(() => {
  const titles: Record<ModalType, string> = { add: '新增用户', edit: '编辑用户' }
  return titles[props.type]
})

const defaultModel = (): UserModel => ({
  mobile: '',
  name: '',
  real_name: '',
  sex: '保密',
  email: '',
  id: 0,
  avatar: null,
  is_super_admin: 0,
})

const formModel = reactive<UserModel>(defaultModel())

const rules: FormRules = {
  mobile: {
    required: true,
    trigger: ['input'],
    validator: (rule: FormItemRule, value: string) => {
      if (!value) return new Error('请输入移动电话')
      if (!/^(\+?\d{1,3})?[-. ]?\(?\d{3}\)?[-. ]?\d{3}[-. ]?\d{4}$|^1[3-9]\d{9}$/.test(value))
        return new Error('移动电话格式不正确')
      return true
    },
  },
  name: {
    required: true,
    message: '请输入昵称',
    trigger: ['input'],
  },
  real_name: {
    required: true,
    message: '请输入姓名',
    trigger: ['input'],
  },
  sex: {
    required: true,
    message: '请选择性别',
  },
  email: {
    type: 'email',
    message: '邮件地址格式不正确',
    trigger: ['input'],
  },
}

//关闭弹窗
const closeModal = () => (modalVisible.value = false)

//提交数据
async function handleSubmit() {
  await formRef.value?.validate()
  const { success } = props.type == 'add' ? await add(formModel) : await update(formModel)
  if (success) {
    props.load()
    closeModal()
  }
}
</script>

<template>
  <n-modal v-model:show="modalVisible" preset="card" :title="title" class="max-w-2xl">
    <n-form ref="formRef" :label-width="80" :model="formModel" :rules="rules">
      <n-grid :cols="24" :x-gap="24">
        <n-form-item-gi :span="12" label="昵称" path="name">
          <n-input v-model:value="formModel.name" placeholder="请输入昵称" />
        </n-form-item-gi>
        <n-form-item-gi :span="12" label="姓名" path="real_name">
          <n-input v-model:value="formModel.real_name" placeholder="请输入姓名" />
        </n-form-item-gi>
        <n-form-item-gi :span="12" label="移动电话" path="mobile">
          <n-input v-model:value="formModel.mobile" placeholder="请输入移动电话" />
        </n-form-item-gi>
        <n-form-item-gi :span="12" label="邮件地址" path="email">
          <n-input v-model:value="formModel.email" placeholder="请输入邮件地址" />
        </n-form-item-gi>
        <n-form-item-gi :span="12" label="性别" path="sex">
          <n-radio-group v-model:value="formModel.sex" name="sex">
            <n-space>
              <n-radio value="男">男</n-radio>
              <n-radio value="女">女</n-radio>
              <n-radio value="保密">保密</n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item-gi>
        <n-form-item-gi :span="12" label="是否是管理员" path="is_super_admin">
          <n-radio-group v-model:value="formModel.is_super_admin" name="is_super_admin">
            <n-space>
              <n-radio :value="1">是</n-radio>
              <n-radio :value="0">否</n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item-gi>
      </n-grid>

      <n-space justify="end">
        <n-button @click="closeModal">取消</n-button>
        <n-button type="primary" @click="handleSubmit">确定</n-button>
      </n-space>
    </n-form>
  </n-modal>
</template>

<style lang="scss" scoped></style>
